package com.example.routeplansystem.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelCommonException;
import com.alibaba.excel.read.listener.PageReadListener;
import com.example.routeplansystem.dao.QuestionNodeDao;
import com.example.routeplansystem.dao.NodeDao;
import com.example.routeplansystem.entity.bo.NodeExcelBO;
import com.example.routeplansystem.entity.bo.QuestionNodeExcelBO;
import com.example.routeplansystem.entity.dto.ResponseEntity;
import com.example.routeplansystem.entity.po.NodePojo;
import com.example.routeplansystem.entity.po.QuestionNodePojo;
import com.example.routeplansystem.exception.ServiceException;
import com.example.routeplansystem.utils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.logging.Handler;
import java.util.stream.Collectors;

@Component
@Configuration
public class BatchImportService {

    @Autowired
    private NodeDao nodeDao;

    @Autowired
    private QuestionNodeDao questionNodeDao;

    public <U> List<U> batchImport(MultipartFile mFile, U type) {
        ExcelUtil.checkFile(mFile);
        InputStream inputStream = null;
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setMsg("成功！！！");
        List<U> list = new ArrayList<>();
        try {
            inputStream = mFile.getInputStream();
            EasyExcel.read(inputStream, type.getClass(), new PageReadListener<U>(dataList -> {
                list.addAll(dataList);
            })).sheet().doRead();
        } catch (ExcelCommonException e) {
            throw new RuntimeException("只允许上传Excel文件");
        } catch (IOException e) {
            throw new RuntimeException("文件IO错误");
        } finally {
            try {
                Objects.requireNonNull(inputStream, "获取文件输入流失败");
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public List<Integer> batchImportClientNode(List<NodeExcelBO> list, Integer userId) {
        List<NodePojo> nodePojos = list.stream()
                .map(node -> node.toPojo(userId)).collect(Collectors.toList());
        List<Integer> errorList = new ArrayList<>();
        for (int i = 0; i < nodePojos.size(); i++) {
            NodePojo node = nodePojos.get(i);
            if (node.getNodeName().length() > 50) throw new ServiceException("客户名称长度大于50,下次从第" + i + 1 + "行,开始导入");
            if (node.getNodeAddress().length() > 50) throw new ServiceException("客户地址长度大于50,下次从第" + i + 1 + "行,开始导入");
            boolean insertFlag = false;
            try {
                insertFlag = nodeDao.insertNode(node);
            } catch (Exception e) {
                errorList.add(node.getClientId());
            }
        }
        return errorList;
    }


    public List<QuestionNodeExcelBO> batchImportQuestionNode(Integer userId, List<QuestionNodeExcelBO> list, Integer questoinId) {
        List<Integer> clientIdList = new ArrayList<>();
        List<String> nodeNameList = new ArrayList<>();
        for (QuestionNodeExcelBO nodeExcelBO : list) {
            clientIdList.add(nodeExcelBO.getCustomerId());
            nodeNameList.add(nodeExcelBO.getCustomerName());
        }

        List<NodePojo> nodePojos1 = nodeDao.selectNodeByUserIdAndNameAndClientId(new HashMap() {{
            put("userId",userId);
            put("clientIdList", clientIdList);
            put("nodeNameList", nodeNameList);
        }});
        List<QuestionNodeExcelBO> notNodePojos = new ArrayList<>();
        for (QuestionNodeExcelBO nodeExcelBO : list) {
            int i = 0;
            for (NodePojo nodePojo : nodePojos1) {
                if (nodePojo.getClientId().equals(nodeExcelBO.getCustomerId()) && nodePojo.getNodeName().equals(nodeExcelBO.getCustomerName()))
                    break;
                i++;
            }
            if (i == nodePojos1.size())
                notNodePojos.add(nodeExcelBO);
        }
        if (notNodePojos.size() == 0) {
            List<QuestionNodePojo> questionNodePojos = list.stream().map(node -> node.toQuestionNodePojo(questoinId)).collect(Collectors.toList());
            questionNodeDao.insertQuestionNodeBatch(questionNodePojos);
        }
        return notNodePojos;
    }
}
